package eerbaar.expression.internal.lib;

import eerbaar.area.IArea;
import eerbaar.context.IContext;
import eerbaar.context.IParams;
import eerbaar.context.ParamFactory;
import eerbaar.elements.IElement;
import eerbaar.game.IGame;

public class CountElementExpression extends AbstractExpression {

    private static final String[] paramNames = new String[] { "name", "count" };

    private int count;

    private IParams params;

    private String target;

    public CountElementExpression() {
        super("countElement");
        this.params = ParamFactory.createParams();
    }

    public CountElementExpression(IParams params) {
        super("countElement");
        this.params = params;

        setup(params);
    }

    @Override
    public boolean execute(IContext model) {
        assert (this.target != null);

        int c = 0;
        IGame game = (IGame) model;
        IArea area = game.getArea();
        IElement[] elements = area.getElements();
        for (IElement element : elements) {
            if (element.getName().equals(this.target)) {
                c++;
            }
        }

        return (c == this.count);
    }

    @Override
    public String[] getParamNames() {

        return paramNames;
    }

    @Override
    public IParams getParams() {

        return this.params;
    }

    public String getTarget() {
        return this.target;
    }

    @Override
    public void setParams(IParams params) {
        this.params = params;
        setup(params);
    }

    public void setTarget(String target) {
        this.target = target;
    }

    private void setup(IParams params) {

        this.target = params.get("name");

        if (params.get("count") != null) {
            this.count = Integer.parseInt(params.get("count"));
        }
    }
}
